package com.rk.jarjuggler.service;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.net.HttpConfigurable;
import org.apache.commons.io.FileUtils;

public class HttpUtil {

    public static final String HTTP_SEPARATOR = "/";

    /**
     * Util for downloading files inside an Intellij plugin
     *
     * @param url
     * @param destination
     * @throws IOException
     */
    public static void copyFile(String url, File destination) throws IOException {
        final HttpConfigurable httpConfigurable =
            (HttpConfigurable) ApplicationManager.getApplication().getComponent("HttpConfigurable");

        if (httpConfigurable != null) {
          httpConfigurable.prepareURL(url);
        }

        FileUtils.copyURLToFile(new URL(url), destination);
    }

    public static File downloadFileToProject(String url, String projectFolder, String subdir) throws IOException {
        String destFileName = getFileName(url);

        String prefix = getPrefix(destFileName);
        String suffix = getSuffix(destFileName);

        File tempFile = FileUtil.createTempFile(prefix, suffix);
        System.out.println("Downloading file");
        HttpUtil.copyFile(url, tempFile);

        File destFile = new File(projectFolder + File.separator + subdir + File.separator + destFileName);
        System.out.println("moving file to destFile = " + destFile);
        FileUtil.createParentDirs(destFile);
        FileUtil.copy(tempFile, destFile);
        return destFile;
    }

    public static String getSuffix(String destFileName) {
        return destFileName.substring(destFileName.length() - 3, destFileName.length());
    }

    public static String getPrefix(String destFileName) {
        return destFileName.substring(0, destFileName.length() - 4);
    }


    public static String getFileName(String url){
        return url.substring(url.lastIndexOf(HTTP_SEPARATOR) + 1, url.length());
    }

    public static String slashify(String currentUrl) {
        return currentUrl.replace("\\", "/");
    }
}
